//
//  LoginVC.m
//  PetAPP
//
//  Created by apple on 16/3/4.
//  Copyright © 2016年 Yuming. All rights reserved.
//

#import "LoginVC.h"
#import "LoginTextField.h"
#import "NetworkingHandle.h"
#import <CommonCrypto/CommonDigest.h>
#import "ForgetPassWordVC.h"


#define WIDTH self.view.frame.size.width


@interface LoginVC () <UITextFieldDelegate>

@property (nonatomic, retain) LoginTextField *textFileOfName;

@property (nonatomic, retain) LoginTextField *textFileOfPassWord;

@property (nonatomic, retain) UIButton *buttonOfLogin;

@end

@implementation LoginVC

- (void)dealloc {

    [_textFileOfName release];
    [_textFileOfPassWord release];
    [_buttonOfLogin release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self createSubViews];
    self.navigationItem.title = @"登录";
}

- (void)createSubViews {
    
    
    
    self.textFileOfName = [[LoginTextField alloc] initWithFrame:CGRectMake(20, 60 + 64, WIDTH - 40, 30)];
    [self.view addSubview:_textFileOfName];
    [_textFileOfName release];
    self.textFileOfName.placeholder = @"用户名/手机号";

    
    self.textFileOfPassWord = [[LoginTextField alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(self.textFileOfName.frame) + 30, WIDTH - 40, 30)];
    [self.view addSubview:_textFileOfPassWord];
    [_textFileOfPassWord release];
    self.textFileOfPassWord.placeholder = @"密码";
    self.textFileOfPassWord.secureTextEntry = YES;
    self.textFileOfPassWord.delegate = self;
    [self.textFileOfPassWord addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    
    
    self.buttonOfLogin = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_buttonOfLogin];
    self.buttonOfLogin.frame = CGRectMake(20, CGRectGetMaxY(self.textFileOfPassWord.frame) + 40, WIDTH - 40, 40);
    self.buttonOfLogin.backgroundColor = [UIColor colorWithRed:0.7721 green:0.7721 blue:0.7721 alpha:1.0];
    [self.buttonOfLogin setTitle:@"登录" forState:UIControlStateNormal];
    self.buttonOfLogin.layer.cornerRadius = 5;
    [self.buttonOfLogin setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.buttonOfLogin.userInteractionEnabled = NO;
    [self.buttonOfLogin addTarget:self action:@selector(handleButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *labelOfForget = [[UILabel alloc] initWithFrame:CGRectMake(25, CGRectGetMaxY(self.buttonOfLogin.frame) + 20, 100, 20)];
    [self.view addSubview:labelOfForget];
    [labelOfForget release];
    UITapGestureRecognizer *tapOfForget = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleLabelAction:)];
    [labelOfForget addGestureRecognizer:tapOfForget];
    [tapOfForget release];
    
    labelOfForget.text = @"忘记密码";
    labelOfForget.textColor = [UIColor colorWithRed:0.5473 green:0.5473 blue:0.5473 alpha:1.0];
    labelOfForget.tag = 1;
    labelOfForget.userInteractionEnabled = YES;
    
    
    UILabel *labelOfRegister = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.buttonOfLogin.frame) - 5 - 100, CGRectGetMaxY(self.buttonOfLogin.frame) + 20, 100, 20)];
    [self.view addSubview:labelOfRegister];
    [labelOfRegister release];
    UITapGestureRecognizer *tapOfRegister = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleLabelAction:)];
    [labelOfRegister addGestureRecognizer:tapOfRegister];
    [tapOfRegister release];
    
    labelOfRegister.textAlignment = NSTextAlignmentRight;
    labelOfRegister.textColor = [UIColor colorWithRed:0.5473 green:0.5473 blue:0.5473 alpha:1.0];
    labelOfRegister.text = @"注册账号";
    labelOfRegister.tag = 2;
    labelOfRegister.userInteractionEnabled = YES;
    
    


}

- (void)textFieldDidChange:(UITextField *)textField {

    if (textField.text.length > 3 && textField == self.textFileOfPassWord){
        self.buttonOfLogin.backgroundColor = [UIColor colorWithRed:255/256.0 green:207/256.0 blue:87/256.0 alpha:1];
        self.buttonOfLogin.userInteractionEnabled = YES;
    }else {
        self.buttonOfLogin.backgroundColor = [UIColor colorWithRed:0.7721 green:0.7721 blue:0.7721 alpha:1.0];
        self.buttonOfLogin.userInteractionEnabled = NO;
    }


}


- (void)handleButtonAction:(UIButton *)button {
    
        /** md5加密密码 */
        const char* str = [self.textFileOfPassWord.text UTF8String];
        unsigned char result[CC_MD5_DIGEST_LENGTH];
        CC_MD5(str, (unsigned int)strlen(str), result);
        
        NSMutableString *hash = [NSMutableString string];
        for (int i = 0; i < 16; i++)
        {
            [hash appendFormat:@"%02X", result[i]];
        }
        NSString *mdfiveString = [hash lowercaseString];
        /** 更改body中的账号和密码传值 */
        NSString *body = [NSString stringWithFormat:@"flag=1&password=%@&service=login&username=%@&version=d1bd83a33f1a841ab7fda32449746cc4", mdfiveString, self.textFileOfName.text];
        [NetworkingHandle handlePassWord:@"http://bbs.chinapet.com/plugin.php?id=leepet_thread:api&action=login" AndBody:body value:@{@"Content-Type" : @"application/x-www-form-urlencoded"} handleBlock:^(id result) {
            if ([[result objectForKey:@"msg"] isEqualToString:@""]) {
                NSDictionary *userinfro = [result objectForKey:@"userinfo"];
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                // 保存状态 , 程序再次启动时的偏好设置
                [user setObject:[userinfro objectForKey:@"uid"] forKey:@"uid"];
                [user setObject:[userinfro objectForKey:@"username"] forKey:@"username"];
                [user setObject:[userinfro objectForKey:@"password"] forKey:@"password"];
                [user setBool:YES forKey:@"loginState"];
                [user synchronize];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"handleData" object:nil userInfo:nil];
                [self.navigationController popViewControllerAnimated:YES];
                [self dismissViewControllerAnimated:YES completion:nil];

            }else {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:[result objectForKey:@"msg"] preferredStyle:UIAlertControllerStyleAlert];
                
                // 添加action
                UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"确定" style:0 handler:nil];
                
                
                [alert addAction:actionOK];
                [self presentViewController:alert animated:YES completion:nil];
                
            }
        }];
    


}

- (void)handleLabelAction:(UITapGestureRecognizer *)tap {
    
    ForgetPassWordVC *forgetVC = [[ForgetPassWordVC alloc] init];
    [self.navigationController pushViewController:forgetVC animated:YES];
    [forgetVC release];
    
    if (tap.view.tag == 1) forgetVC.flag = YES;
    else forgetVC.flag = NO;

}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
